// 参数表数据更新工具
// 用于仅对表C.383、C.385、C.386、C.393、C.394更新数据类型和计量类列
// 其他表格继续使用0606文件原始数据

export interface ParameterTableUpdate {
  tableName: string;
  parameters: {
    [key: number]: {
      dataType: string;
      measurementType: string;
    };
  };
}

// 需要使用0618数据更新的特定表格标识符
const TARGET_TABLES = [
  'C.383', 'BAS377', // 开关柜
  'C.385', 'BAS379', // 低压开关柜  
  'C.386', 'BAS380', // 配电箱
  'C.393', 'BAS387', // 照明设备
  'C.394', 'BAS388'  // 普通灯具
];

// 基于0618-石楼油库实体对象分类表.csv的数据
export const parameterTableUpdates: ParameterTableUpdate[] = [
  {
    tableName: "表 C.383    BAS377 开关柜基础参数表",
    parameters: {
      1: { dataType: "字符型", measurementType: "—" },
      2: { dataType: "数值型", measurementType: "电压 2" },
      3: { dataType: "数值型", measurementType: "电流 1" },
      4: { dataType: "字符型", measurementType: "—" },
      5: { dataType: "数值型", measurementType: "频率 1" },
      6: { dataType: "日期型", measurementType: "—" },
      7: { dataType: "数值型", measurementType: "电流 2" },
      8: { dataType: "字符型", measurementType: "—" },
      9: { dataType: "字符型", measurementType: "—" },
      10: { dataType: "字符型", measurementType: "—" },
      11: { dataType: "数值型", measurementType: "电压 2" },
      12: { dataType: "数值型", measurementType: "电流 1" },
      13: { dataType: "字符型", measurementType: "—" },
      14: { dataType: "数值型", measurementType: "无功功率" },
      15: { dataType: "日期型", measurementType: "—" },
      16: { dataType: "字符型", measurementType: "—" },
      17: { dataType: "数值型", measurementType: "电压 2" },
      18: { dataType: "字符型", measurementType: "—" },
      19: { dataType: "字符型", measurementType: "—" },
      20: { dataType: "数值型", measurementType: "视在功率 1" },
      21: { dataType: "数值型", measurementType: "视在功率 1" },
      22: { dataType: "数值型", measurementType: "视在功率 1" }
    }
  },
  {
    tableName: "表 C.385    BAS379 低压开关柜基础参数表",
    parameters: {
      1: { dataType: "字符型", measurementType: "—" },
      2: { dataType: "数值型", measurementType: "电压 2" },
      3: { dataType: "数值型", measurementType: "电流 1" },
      4: { dataType: "字符型", measurementType: "—" },
      5: { dataType: "数值型", measurementType: "频率 1" },
      6: { dataType: "日期型", measurementType: "—" },
      7: { dataType: "数值型", measurementType: "电流 2" },
      8: { dataType: "字符型", measurementType: "—" },
      9: { dataType: "字符型", measurementType: "—" },
      10: { dataType: "字符型", measurementType: "—" },
      11: { dataType: "数值型", measurementType: "电压 2" },
      12: { dataType: "数值型", measurementType: "电流 1" },
      13: { dataType: "字符型", measurementType: "—" },
      14: { dataType: "数值型", measurementType: "无功功率" },
      15: { dataType: "日期型", measurementType: "—" },
      16: { dataType: "字符型", measurementType: "—" },
      17: { dataType: "数值型", measurementType: "电压 2" },
      18: { dataType: "字符型", measurementType: "—" },
      19: { dataType: "字符型", measurementType: "—" },
      20: { dataType: "数值型", measurementType: "视在功率 1" },
      21: { dataType: "数值型", measurementType: "视在功率 1" },
      22: { dataType: "数值型", measurementType: "视在功率 1" }
    }
  },
  {
    tableName: "表 C.386    BAS380 配电箱基础参数表",
    parameters: {
      1: { dataType: "字符型", measurementType: "—" },
      2: { dataType: "字符型", measurementType: "—" },
      3: { dataType: "字符型", measurementType: "—" },
      4: { dataType: "字符型", measurementType: "—" },
      5: { dataType: "字符型", measurementType: "—" },
      6: { dataType: "数值型", measurementType: "电压 2" },
      7: { dataType: "数值型", measurementType: "电流 1" },
      8: { dataType: "字符型", measurementType: "—" }
    }
  },
  {
    tableName: "表 C.393    BAS387 照明设备基础参数表",
    parameters: {
      1: { dataType: "字符型", measurementType: "—" },
      2: { dataType: "字符型", measurementType: "—" },
      3: { dataType: "字符型", measurementType: "—" },
      4: { dataType: "字符型", measurementType: "—" },
      5: { dataType: "字符型", measurementType: "—" }
    }
  },
  {
    tableName: "表 C.394    BAS388 普通灯具基础参数表",
    parameters: {
      1: { dataType: "字符型", measurementType: "—" },
      2: { dataType: "字符型", measurementType: "—" },
      3: { dataType: "字符型", measurementType: "—" },
      4: { dataType: "字符型", measurementType: "—" },
      5: { dataType: "字符型", measurementType: "—" }
    }
  }
];

// 检查是否为需要更新的目标表格
function isTargetTable(sheetData: any): boolean {
  if (!sheetData) return false;
  
  // 检查工作表名称
  if (sheetData.sheetName) {
    const sheetName = sheetData.sheetName.toLowerCase();
    if (TARGET_TABLES.some(table => sheetName.includes(table.toLowerCase()))) {
      return true;
    }
  }
  
  // 检查表格内容中的标题行
  if (sheetData.rows && sheetData.rows.length > 0) {
    for (let i = 0; i < Math.min(5, sheetData.rows.length); i++) {
      const row = sheetData.rows[i];
      if (row && row[0]) {
        const firstCell = row[0].toString().toLowerCase();
        if (TARGET_TABLES.some(table => firstCell.includes(table.toLowerCase()))) {
          return true;
        }
      }
    }
  }
  
  return false;
}

// 应用更新的函数 - 仅对目标表格应用
export function applyParameterTableUpdates(sheetData: any): any {
  if (!sheetData || !sheetData.rows) return sheetData;

  // 检查是否为需要更新的目标表格
  if (!isTargetTable(sheetData)) {
    console.log('跳过非目标表格:', sheetData.sheetName);
    return sheetData; // 直接返回原始数据，不做任何修改
  }

  console.log('应用参数表更新到目标表格:', sheetData.sheetName);

  // 复制数据以避免修改原始数据
  const updatedData = JSON.parse(JSON.stringify(sheetData));
  
  // 确定当前表格对应的更新配置
  let currentUpdate = null;
  
  // 方法1: 直接通过表格标题行查找
  if (updatedData.rows && updatedData.rows.length > 0) {
    // 检查前几行是否包含表格标题
    for (let i = 0; i < Math.min(5, updatedData.rows.length); i++) {
      const row = updatedData.rows[i];
      if (row && row[0]) {
        const firstCell = row[0].toString();
        if (firstCell.includes('C.383') || firstCell.includes('BAS377')) {
          currentUpdate = parameterTableUpdates[0];
          break;
        } else if (firstCell.includes('C.385') || firstCell.includes('BAS379')) {
          currentUpdate = parameterTableUpdates[1];
          break;
        } else if (firstCell.includes('C.386') || firstCell.includes('BAS380')) {
          currentUpdate = parameterTableUpdates[2];
          break;
        } else if (firstCell.includes('C.393') || firstCell.includes('BAS387')) {
          currentUpdate = parameterTableUpdates[3];
          break;
        } else if (firstCell.includes('C.394') || firstCell.includes('BAS388')) {
          currentUpdate = parameterTableUpdates[4];
          break;
        }
      }
    }
  }
  
  // 方法2: 通过工作表名称查找（备用方法）
  if (!currentUpdate && sheetData.sheetName) {
    const sheetName = sheetData.sheetName.toLowerCase();
    if (sheetName.includes("c.383") || sheetName.includes("bas377")) {
      currentUpdate = parameterTableUpdates[0];
    } else if (sheetName.includes("c.385") || sheetName.includes("bas379")) {
      currentUpdate = parameterTableUpdates[1];
    } else if (sheetName.includes("c.386") || sheetName.includes("bas380")) {
      currentUpdate = parameterTableUpdates[2];
    } else if (sheetName.includes("c.393") || sheetName.includes("bas387")) {
      currentUpdate = parameterTableUpdates[3];
    } else if (sheetName.includes("c.394") || sheetName.includes("bas388")) {
      currentUpdate = parameterTableUpdates[4];
    }
  }

  if (!currentUpdate) {
    console.log('未找到匹配的更新配置，返回原始数据');
    return updatedData;
  }

  // 查找表头行和数据类型、计量类列的索引
  let headerRowIndex = -1;
  let dataTypeIndex = -1;
  let measurementTypeIndex = -1;
  
  // 查找包含"序号"、"中文名称"等关键词的行作为表头
  for (let i = 0; i < Math.min(10, updatedData.rows.length); i++) {
    const row = updatedData.rows[i];
    if (row && row.length > 0) {
      // 检查是否包含表头关键词
      const rowStr = row.join('').toLowerCase();
      if (rowStr.includes('序号') && rowStr.includes('中文名称') && 
          (rowStr.includes('数据类型') || rowStr.includes('计量类'))) {
        headerRowIndex = i;
        
        // 查找列索引
        dataTypeIndex = row.findIndex((cell: any) => 
          cell && cell.toString().includes('数据类型')
        );
        measurementTypeIndex = row.findIndex((cell: any) => 
          cell && cell.toString().includes('计量类')
        );
        break;
      }
    }
  }

  if (headerRowIndex === -1 || dataTypeIndex === -1 || measurementTypeIndex === -1) {
    console.log('未找到表头行或数据类型/计量类列:', { 
      headerRowIndex, 
      dataTypeIndex, 
      measurementTypeIndex,
      sheetName: sheetData.sheetName
    });
    return updatedData;
  }

  // 更新数据行（从表头行之后开始）
  for (let i = headerRowIndex + 1; i < updatedData.rows.length; i++) {
    const row = updatedData.rows[i];
    if (!row || row.length === 0) continue;

    // 获取序号（第一列）
    const sequenceNumber = row[0];
    if (!sequenceNumber) continue;

    // 解析序号
    let seqNum = null;
    if (typeof sequenceNumber === 'number') {
      seqNum = sequenceNumber;
    } else if (typeof sequenceNumber === 'string') {
      seqNum = parseInt(sequenceNumber, 10);
    }

    if (!seqNum || isNaN(seqNum)) continue;

    // 查找对应的更新数据
    const updateData = currentUpdate.parameters[seqNum];
    if (!updateData) continue;

    // 扩展行长度以确保可以设置新值
    while (row.length <= Math.max(dataTypeIndex, measurementTypeIndex)) {
      row.push(null);
    }

    // 更新数据类型列
    row[dataTypeIndex] = updateData.dataType;
    
    // 更新计量类列
    row[measurementTypeIndex] = updateData.measurementType;
  }

  console.log('参数表更新完成:', {
    表格: currentUpdate.tableName,
    更新参数数量: Object.keys(currentUpdate.parameters).length,
    表头行: headerRowIndex,
    数据类型列: dataTypeIndex,
    计量类列: measurementTypeIndex
  });

  return updatedData;
}

// 批量更新多个工作表
export function updateParameterTablesInSheets(sheets: any[]): any[] {
  return sheets.map(sheet => applyParameterTableUpdates(sheet));
} 